/*
 * Eugen Stoian <stoian.e@gmail.com> 2010
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "OpEQNode.h"
#include "ValueNode.h"
#include "OpSUBNode.h"


static Real opEQ(const Real& left,const Real& right) {
    if(left==right)
        return 1.0;
    return 0.0;
}


static SmartPtr<ExpressionTreeNode> opEQDerivativeBuilder(SmartPtr<ExpressionTreeNode> node, const QString&) {
    if(!node)
        return 0;
    if(node->info()!=EQ_SYMBOL)
        return 0;
    if(!node->right())
        return 0;
    if(!node->left())
        return 0;
    return new ValueNode(0.0);
}

OpEQNode::OpEQNode()
        :RelationalOpNode(EQ_SYMBOL, &opEQ, &opEQDerivativeBuilder){
}

ExpressionTreeNode* OpEQNode::copy() const {
    SmartPtr<ExpressionTreeNode> left = 0;
    SmartPtr<ExpressionTreeNode> right = 0;
    ExpressionTreeNode *root = 0;
    if(_left)
        left = _left->copy();
    if(_right)
        right = _right->copy();
    root = new OpEQNode();
    root->setLeft(left);
    root->setRight(right);
    return root;
}

int OpEQNode::precedence() const {
    return EQ_PRECEDENCE;
}

SmartPtr<ExpressionTreeNode> OpEQNode::firstLevelSimplification() const{
    SmartPtr<ExpressionTreeNode> root = 0;
    QString branchPath;
    if(!_left || !_right)
        return 0;
    SmartPtr<ExpressionTreeNode> left = _left->firstLevelSimplification();
    if(!left)
        return 0;
    SmartPtr<ExpressionTreeNode> right = _right->firstLevelSimplification();
    if(!right){
        return 0;
    }
    if(left->isValue() && right->isValue()){
        root = new ValueNode((*_op)(left->eval(),right->eval()));
        return root;
    }
    if(!right->isValue() || !right->eval().isZero()) {
        root = new OpSUBNode();
        root->setLeft(left);
        root->setRight(right);
        left = root->firstLevelSimplification();
        root = new OpEQNode();
        root->setLeft(left);
        root->setRight(new ValueNode(0.0));
        return root;
    }
    root = new OpEQNode();
    root->setLeft(left);
    root->setRight(right);
    return root;
}
